<template>
  <div class="container fade-in">
    <div class="header">
      <h2 class="section-title">支付平台管理</h2>
      <div class="actions">
        <button class="btn primary" @click="toggleCreateForm">新增平台</button>
      </div>
    </div>

    <!-- 筛选区域：对齐用户管理页面样式 -->
    <div class="card slide-up" style="animation-delay: 0.08s">
      <div class="filters">
        <div class="filter-row">
          <span class="filter-label">平台名称</span>
          <input
            v-model="filters.key"
            type="text"
            placeholder="输入平台名称进行搜索"
            class="input flex-1"
            @input="debouncedSearch"
          />
          <button class="btn secondary" @click="resetFilters">重置</button>
          <span class="filter-label">每页</span>
          <select v-model.number="pagination.pageSize" @change="changePageSize" class="select">
            <option :value="10">10</option>
            <option :value="20">20</option>
            <option :value="50">50</option>
          </select>
          <span class="filter-label">条</span>
        </div>
      </div>
    </div>

    <!-- 新增平台表单 -->
    <div v-if="showCreate" class="card slide-up" style="animation-delay: 0.05s">
      <h3 class="section-title">新增支付平台</h3>
      <div class="form-grid">
        <div class="field">
          <label>名称<span class="required">*</span></label>
          <input v-model="createForm.name" type="text" placeholder="请输入平台名称" class="input" />
        </div>
        <div class="field">
          <label>收单服务商ID</label>
          <input v-model="createForm.acqSpId" type="text" placeholder="例如：562294004495976" class="input" />
        </div>
        <div class="field">
          <label>应用ID</label>
          <input v-model="createForm.appId" type="text" placeholder="渠道应用AppId" class="input" />
        </div>
        <div class="field">
          <label>回调URL</label>
          <input v-model="createForm.callbackUrl" type="text" placeholder="支付结果回调地址" class="input" />
        </div>
        <div class="field">
          <label>密钥</label>
          <input v-model="createForm.secretKey" type="text" placeholder="平台密钥" class="input" />
        </div>
        <div class="field">
          <label>备注</label>
          <input v-model="createForm.description" type="text" placeholder="平台说明备注" class="input" />
        </div>
        <div class="field wide">
          <label>扩展属性</label>
          <textarea v-model="createForm.extraProperties" rows="3" placeholder='可填写JSON，如 {"k":"v"}' class="textarea"></textarea>
        </div>
      </div>
      <div class="actions">
        <button class="btn primary" :disabled="createLoading" @click="submitCreate">
          <span class="icon">➕</span> 提交新增
        </button>
        <button class="btn secondary" :disabled="createLoading" @click="resetCreateForm">重置</button>
        <button class="btn" :disabled="createLoading" @click="toggleCreateForm">取消</button>
      </div>
      <div v-if="createLoading" class="info-msg">正在提交，请稍候...</div>
    </div>

    <!-- 列表卡片：对齐用户管理页面样式 -->
    <div class="card slide-up" style="animation-delay: 0.1s">
      <div class="table-header">
        <div class="left">
          <span class="subtitle">平台列表</span>
        </div>
        <div class="right actions">
          <button class="btn secondary" @click="loadPlatforms">刷新</button>
        </div>
      </div>

      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>加载平台列表中...</p>
      </div>
      <table v-else class="table">
        <thead>
          <tr>
            <th>名称</th>
            <th>平台编号</th>
            <th>接单</th>
            <th>收单服务商ID</th>
            <th>应用ID</th>
            <th>回调URL</th>
            <th>虚拟余额</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="platforms.length === 0" class="empty-row">
            <td colspan="9" class="empty">暂无数据</td>
          </tr>
          <tr v-else v-for="p in platforms" :key="p.id" class="data-row">
            <td>{{ p.name || '-' }}</td>
            <td>{{ p.code || '-' }}</td>
            <td>
              <span class="badge" :class="acceptBadge(p.acceptOrder)">{{ formatAccept(p.acceptOrder) }}</span>
            </td>
            <td>{{ p.acqSpId || '-' }}</td>
            <td>{{ p.appId || '-' }}</td>
            <td>
              <template v-if="p.callbackUrl">
                <a :href="p.callbackUrl" target="_blank" rel="noopener" class="link">{{ p.callbackUrl }}</a>
              </template>
              <template v-else>-</template>
            </td>
            <td class="money">{{ fmtMoney(p.virtualBalance) }}</td>
            <td>{{ formatDate(p.creationTime) }}</td>
            <td>
              <button
                class="btn primary sm"
                :disabled="!auth.isPlatformSuperAdmin"
                :title="!auth.isPlatformSuperAdmin ? '仅平台超级管理员可操作提现' : '发起提现'"
                @click="openWithdrawModal(p)"
              >提现</button>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-if="pagination.total > 0" class="pagination">
        <div class="pagination-info">
          共 {{ pagination.total }} 条记录，第 {{ pagination.current }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
        </div>
        <div class="pagination-controls">
          <button class="btn secondary sm" :disabled="pagination.current <= 1" @click="changePage(pagination.current - 1)">上一页</button>
          <button class="btn secondary sm" :disabled="pagination.current >= Math.ceil(pagination.total / pagination.pageSize)" @click="changePage(pagination.current + 1)">下一页</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 提现二次弹窗 -->
  <div v-if="withdrawModalVisible" class="modal-backdrop" @click.self="closeWithdrawModal">
    <div class="modal">
      <h3 class="modal-title">发起提现</h3>
      <p class="modal-sub">平台：{{ withdrawPlatform?.name }}（虚拟余额：{{ fmtMoney(withdrawPlatform?.virtualBalance) }}）</p>
      <div class="modal-body">
        <div v-if="withdrawMerchants.length > 1" class="field">
          <label>选择商户<span class="required">*</span></label>
          <select v-model="selectedMerchantId" class="select">
            <option v-for="m in withdrawMerchants" :key="m.id" :value="m.id">{{ m.name || m.merchantName || m.merchantCode || m.id }}</option>
          </select>
        </div>
        <div class="field">
          <label>提现金额（元）<span class="required">*</span></label>
          <input class="input" type="number" step="0.01" min="0" v-model="withdrawAmountYuan" placeholder="请输入金额，最多两位小数" />
          <small class="inline">不可超过虚拟余额；仅平台超级管理员可提交</small>
        </div>
        <p v-if="withdrawError" class="error">{{ withdrawError }}</p>
      </div>
      <div class="modal-actions">
        <button class="btn" :disabled="withdrawSubmitting" @click="closeWithdrawModal">取消</button>
        <button class="btn primary" :disabled="withdrawSubmitting || !auth.isPlatformSuperAdmin" @click="submitWithdraw">{{ withdrawSubmitting ? '提交中...' : '确认提现' }}</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * 文件级注释：
 * 支付平台管理页面组件，提供支付平台列表查询与新增能力。
 * 仅在 H5 项目中编写/修改；所有接口返回以 `code === 0` 判断成功。
 */
import { ref, reactive, onMounted } from 'vue'
import { useAuthStore } from '../stores/auth'
import { isSuccess } from '../services/types'
import { PaymentPlatformService, type PaymentPlatformResponse, type PaymentPlatformCreateRequest } from '../services/paymentPlatform'
import { PaymentService } from '../services/payment'
import { OrganizationService, type MerchantResponse } from '../services/organization'

// 列表加载状态
const loading = ref(false)
// 新增加载状态
const createLoading = ref(false)
// 是否展示新增表单
const showCreate = ref(false)
// 平台列表
const platforms = ref<PaymentPlatformResponse[]>([])
// 分页信息
const pagination = reactive({ current: 1, pageSize: 10, total: 0 })

// 筛选模型（与用户管理一致）
const filters = reactive<{ key: string }>({ key: '' })

// 新增表单模型
const createForm = reactive<PaymentPlatformCreateRequest>({
  name: '',
  description: '',
  acqSpId: '',
  appId: '',
  callbackUrl: '',
  secretKey: '',
  extraProperties: ''
})

// 认证状态（用于角色权限判断）
const auth = useAuthStore()

// 提现弹窗状态与表单
const withdrawModalVisible = ref(false)
const withdrawPlatform = ref<PaymentPlatformResponse | null>(null)
const withdrawMerchants = ref<MerchantResponse[]>([])
const selectedMerchantId = ref<string>('')
const withdrawAmountYuan = ref<string>('')
const withdrawSubmitting = ref(false)
const withdrawError = ref('')

/**
 * 函数级注释：格式化时间为中文本地字符串
 * @param v 原始时间字符串
 * @returns 格式化后的中文本地时间；无法解析则返回“-”或原值
 * @throws 无异常（内部 try-catch 防御）
 */
function formatDate(v?: string) {
  if (!v) return '-'
  try { return new Date(v).toLocaleString('zh-CN') } catch { return v }
}

/**
 * 函数级注释：将布尔/数值映射为“是/否”
 * @param v 原始值（true/false/0/1/undefined）
 * @returns 中文“是/否”或“-”
 * @throws 无异常（纯映射）
 */
function formatAccept(v: any): string {
  if (v === null || v === undefined || v === '') return '-'
  const n = typeof v === 'string' ? Number(v) : v
  return (n === 1 || n === true) ? '是' : '否'
}

/**
 * 函数级注释：根据接单状态返回徽章样式类名
 * @param v 原始值（true/false/0/1）
 * @returns 'active' | 'inactive' 徽章状态类名
 * @throws 无异常（纯映射）
 */
function acceptBadge(v: any): string {
  const n = typeof v === 'string' ? Number(v) : v
  return (n === 1 || n === true) ? 'active' : 'inactive'
}

/**
 * 函数级注释：金额格式化（单位分 -> 元，保留两位小数）
 * @param v 原始金额，单位分（number/string/undefined）
 * @returns 格式化后的人民币字符串，例如："¥1,234.56"；无值返回 "-"
 * @throws 无异常（内部进行类型与数值防御）
 */
function fmtMoney(v?: number | string): string {
  if (v === null || v === undefined || v === '') return '-'
  const n = typeof v === 'string' ? Number(v) : v
  if (!Number.isFinite(n)) return '-'
  const yuan = n / 100
  try {
    return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(yuan)
  } catch {
    return `¥${yuan.toFixed(2)}`
  }
}

/**
 * 函数级注释：切换新增表单显示/隐藏
 * @returns void
 * @throws 无异常
 */
function toggleCreateForm() { showCreate.value = !showCreate.value }

/**
 * 函数级注释：重置新增表单
 * @returns void
 * @throws 无异常
 */
function resetCreateForm() {
  createForm.name = ''
  createForm.description = ''
  createForm.acqSpId = ''
  createForm.appId = ''
  createForm.callbackUrl = ''
  createForm.secretKey = ''
  createForm.extraProperties = ''
}

/**
 * 函数级注释：提交新增支付平台
 * @returns Promise<void> 无返回值，提交后刷新列表
 * @throws 可能抛出网络或服务端异常（axios 错误）
 */
async function submitCreate(): Promise<void> {
  if (!createForm.name || !createForm.name.trim()) {
    alert('请填写平台名称')
    return
  }
  try {
    createLoading.value = true
    const res = await PaymentPlatformService.addPaymentPlatform({
      name: createForm.name.trim(),
      description: createForm.description || undefined,
      acqSpId: createForm.acqSpId || undefined,
      appId: createForm.appId || undefined,
      callbackUrl: createForm.callbackUrl || undefined,
      secretKey: createForm.secretKey || undefined,
      extraProperties: createForm.extraProperties || undefined
    })
    if (isSuccess(res)) {
      alert('新增成功')
      toggleCreateForm()
      resetCreateForm()
      // 重新加载列表
      pagination.current = 1
      await loadPlatforms()
    } else {
      alert(res.message || '新增失败')
    }
  } catch (e: any) {
    alert(e?.message || '提交失败')
    console.error('新增支付平台异常:', e)
  } finally {
    createLoading.value = false
  }
}

/**
 * 函数级注释：加载支付平台列表
 * @returns Promise<void> 无返回值，直接更新响应式列表与分页总数
 * @throws 可能抛出网络或服务端异常（axios 错误）
 */
async function loadPlatforms(): Promise<void> {
  loading.value = true
  try {
    const res = await PaymentPlatformService.getPaymentPlatformList(
      pagination.current,
      pagination.pageSize,
      filters.key?.trim()
    )
    if (isSuccess(res) && res.data) {
      platforms.value = res.data.data || []
      pagination.total = res.data.total || 0
    } else {
      platforms.value = []
      pagination.total = 0
      console.warn('获取支付平台列表失败:', res?.message)
    }
  } catch (e) {
    platforms.value = []
    pagination.total = 0
    console.error('接口异常:', e)
  } finally {
    loading.value = false
  }
}

/**
 * 函数级注释：输入框防抖搜索平台名称
 * @returns void
 * @throws 无异常（内部仅重置与触发加载）
 */
let searchTimer: any = null
function debouncedSearch(): void {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    pagination.current = 1
    loadPlatforms()
  }, 300)
}

/**
 * 函数级注释：切换页码
 * @param page 目标页码（数字）
 * @returns void
 * @throws 无异常
 */
function changePage(page: number): void {
  const max = Math.max(1, Math.ceil(pagination.total / pagination.pageSize))
  const target = Math.min(Math.max(1, page), max)
  if (target !== pagination.current) {
    pagination.current = target
    loadPlatforms()
  }
}

/**
 * 函数级注释：切换每页条数
 * @returns void
 * @throws 无异常
 */
function changePageSize(): void {
  pagination.current = 1
  loadPlatforms()
}

/**
 * 函数级注释：重置筛选条件并刷新列表
 * @returns void
 * @throws 无异常
 */
function resetFilters(): void {
  filters.key = ''
  pagination.current = 1
  loadPlatforms()
}

/**
 * 函数级注释：打开提现弹窗（含权限与商户筛选）
 * @param p 平台行对象（包含 acqSpId 与 virtualBalance）
 * @returns void 无返回值
 * @throws 可能抛出网络异常：拉取商户列表失败
 */
/**
 * 函数级注释：打开平台提现弹窗（平台方不再依赖商户选择）
 * @param p 选中的支付平台对象
 * @returns void 无返回值
 * @throws 无显式抛出（仅权限与状态校验）
 */
async function openWithdrawModal(p: PaymentPlatformResponse): Promise<void> {
  if (!auth.isPlatformSuperAdmin) {
    alert('仅平台超级管理员可操作提现')
    return
  }
  withdrawError.value = ''
  withdrawAmountYuan.value = ''
  withdrawPlatform.value = p
  // 平台方提现不再需要选择商户，直接打开弹窗
  withdrawMerchants.value = []
  selectedMerchantId.value = ''
  withdrawModalVisible.value = true
}

/**
 * 函数级注释：关闭提现弹窗
 * @returns void 无返回值
 * @throws 无
 */
function closeWithdrawModal(): void {
  withdrawModalVisible.value = false
  withdrawPlatform.value = null
  withdrawMerchants.value = []
  selectedMerchantId.value = ''
  withdrawAmountYuan.value = ''
  withdrawError.value = ''
}

/**
 * 函数级注释：提交提现请求（校验金额不得超过虚拟余额）
 * @returns Promise<void> 无返回值
 * @throws 可能抛出网络异常（接口请求失败）
 */
/**
 * 函数级注释：提交平台分账提现请求（校验金额不得超过虚拟余额）
 * @returns Promise<void> 无返回值
 * @throws 可能抛出网络异常（接口请求失败）
 */
async function submitWithdraw(): Promise<void> {
  if (!auth.isPlatformSuperAdmin) {
    withdrawError.value = '仅平台超级管理员可提交'
    return
  }
  const p = withdrawPlatform.value
  if (!p) {
    withdrawError.value = '平台信息缺失'
    return
  }
  // 统一以字符串进行裁剪，避免 input[type="number"] 返回数字导致 .trim 报错
  const amountStr = String(withdrawAmountYuan.value ?? '').trim()
  if (!amountStr) {
    withdrawError.value = '请输入提现金额'
    return
  }
  // 校验金额格式（最多两位小数，正数）
  const amountNum = Number(amountStr)
  if (!Number.isFinite(amountNum) || amountNum <= 0) {
    withdrawError.value = '金额格式不正确'
    return
  }
  const cents = Math.round(amountNum * 100)
  const vb = Number(p.virtualBalance || 0)
  if (cents > vb) {
    withdrawError.value = '提现金额不能超过虚拟余额'
    return
  }
  try {
    withdrawSubmitting.value = true
    // 后端签名为 PlatformSplitWithdrawal(long amount)，此处直接传入“分”为单位的整数
    const resp = await PaymentService.platformSplitWithdrawal(cents)
    if (isSuccess(resp)) {
      alert('发起提现成功')
      closeWithdrawModal()
      // 提现后刷新平台列表（余额可能变化）
      await loadPlatforms()
    } else {
      withdrawError.value = resp.message || '提现失败'
    }
  } catch (e: any) {
    withdrawError.value = e?.message || '提交异常'
  } finally {
    withdrawSubmitting.value = false
  }
}

/**
 * 生命周期：组件挂载后加载列表
 */
onMounted(() => { loadPlatforms() })
</script>

<style scoped>
.form-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: var(--space-4);
}
.field { display: flex; flex-direction: column; gap: var(--space-2); }
.field.wide { grid-column: 1 / span 2; }
.required { color: var(--danger); margin-left: 4px; }
.inline { margin: 0 var(--space-2); color: var(--text-secondary); }
.loading-state { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-4); }
.spinner { width: 20px; height: 20px; border: 2px solid var(--border); border-top-color: var(--primary); border-radius: 50%; animation: spin 0.8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.empty { color: var(--text-secondary); text-align: center; }
.table-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: var(--space-3); }
.subtitle { color: var(--text-secondary); }
.badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 12px; border: 1px solid transparent; }
.badge.active { background: #ecfdf5; color: #065f46; border-color: #a7f3d0; }
.badge.inactive { background: #f3f4f6; color: #374151; border-color: #e5e7eb; }
.link { color: var(--primary); text-decoration: none; }
.link:hover { text-decoration: underline; }

/* 对齐用户管理页面的表格与筛选样式 */
.filters { padding: var(--space-4); }
.filter-row { display: flex; align-items: center; gap: var(--space-3); }
.filter-label { color: var(--text-secondary); }
.flex-1 { flex: 1; min-width: 240px; }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { padding: 12px; border-bottom: 1px solid var(--border); }
.table thead th { text-align: left; color: var(--text-secondary); font-weight: 600; }
.data-row .actions { display:flex; gap: 8px; }
.pagination { display:flex; align-items:center; justify-content:space-between; padding: var(--space-3); }
.pagination-info { color: var(--text-secondary); }

/* 二次弹窗样式 */
.modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.35);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 50;
}
.modal {
  background: #fff;
  width: 90%;
  max-width: 520px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.15);
  padding: var(--space-4);
}
.modal-title { font-size: 18px; font-weight: 600; margin-bottom: var(--space-2); }
.modal-sub { color: var(--text-secondary); margin-bottom: var(--space-3); }
.modal-body { display: flex; flex-direction: column; gap: var(--space-3); }
.modal-actions { display: flex; justify-content: flex-end; gap: var(--space-3); margin-top: var(--space-3); }
.error { color: var(--danger); }
.btn.sm { padding: 6px 10px; font-size: 12px; }
</style>
